package chapter1.bagqueuestack.example;

import edu.princeton.cs.algs4.StdIn;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author quanlinlin on 2018/12/1 16:32.
 * @version 1.0
 */
public class Stack<Item> implements Iterable<Item> {

    private Node first;

    private int N;

    @NotNull
    @Override
    public Iterator<Item> iterator() {
        return new stackIterator(first);
    }


    private class Node {
        Item item;
        Node next;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void push(Item item) {
        //向栈顶添加元素
        Node oldfirst = this.first;
        first = new Node();
        first.next = oldfirst;
        first.item = item;
        N++;
    }

    public Item pop() {
        //从栈顶弹出元素
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }


    /**
     * @return 返回栈中最近添加的元素，而不删除它
     */
    public Item peek() {
        if (isEmpty()) {
            //throw new NullPointerException("stack is empty");
            throw new NoSuchElementException("Stack underflow");
        } /*else {
            Item pop = pop();
            push(pop);
            return pop;
        }*/
        return first.item;
    }

    /**
     * 返回栈的一个副本
     *
     * @param stringStack
     * @return
     */
    public Stack<String> copy(Stack<String> stringStack) {
        Stack<String> temp = new Stack<>();
        for (String s : stringStack) {
            temp.push(s);
        }
        return temp;
    }

    public static void main(String[] args) {
        //创建一个栈并根据输入中的指示压入或者弹出字符串
        Stack<String> s = new Stack<>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) {
                s.push(item);
            } else if (!s.isEmpty()) {
                System.out.print(s.pop() + " ");
            }
        }
        System.out.println("(" + s.size() + " left on stack)");
    }

    private class stackIterator implements Iterator<Item> {

        private Node current;

        public stackIterator(Node node) {
            current = node;
        }

        @Override
        public boolean hasNext() {
            return current.next != null;
        }

        @Override
        public Item next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return null;
        }

    }
}
